//
//  MBLoginByCodeVC.swift
//  Merchants
//
//  Created by kingly on 2020/7/16.
//  Copyright © 2020 VALUABLE JADE(SHENZHEN) JEWELRY JADE Co.,Ltd. All rights reserved.
//

import UIKit
import SwiftyJSON
import DigitInputView

class MBLoginByCodeVC: BYBaseViewController, DigitInputViewDelegate {
    
    var phonetext : String?
    
    var areaNo: String = "+86"
    
    var isCounting: Bool = false
    
    var remainingSeconds: Int = 60
    
    let smsBtn = BYCountDownButton()
    
    let digitInput = DigitInputView()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let _ = digitInput.becomeFirstResponder()
    }
    
    deinit {
        smsBtn.isCounting = false
    }
    
    func setupUI() {
        let cancelBtn = Button(image: "nav_back")
        cancelBtn.action {[weak self] (_) in
            self?.navigationController?.popViewController(animated: true)
        }
        view.addSubview(cancelBtn)
        
        let tip1Lb = Label(font: .systemFont(ofSize: 30, weight: .medium), textColor: kColor_textBlack, defaultText: "输入验证码")
        view.addSubview(tip1Lb)
        let tip2Lb = Label(font: .systemFont(ofSize: 14, weight: .medium), textColor: kColor_textGray, defaultText: "短信已发送至 +86 \(phonetext ?? "--")")
        view.addSubview(tip2Lb)
        
        digitInput.numberOfDigits = 6
        digitInput.bottomBorderColor = kColor_lineGrayColor
        digitInput.nextDigitBottomBorderColor = kColor_lightBlack
        digitInput.textColor = kColor_textBlack
        digitInput.acceptableCharacters = "0123456789"
        digitInput.keyboardType = .decimalPad
        digitInput.font = UIFont.systemFont(ofSize: 30, weight: .medium)
        digitInput.animationType = .spring
        digitInput.keyboardAppearance = .default
        digitInput.delegate = self
        view.addSubview(digitInput)
        
        smsBtn.isCounting = isCounting
        smsBtn.remainingSeconds = remainingSeconds
        smsBtn.addTarget(self, action: #selector(smsBtnTouchEvent(sender:)), for: .touchUpInside)
        view.addSubview(smsBtn)
        
        //layoutUI
        cancelBtn.snp.makeConstraints { (make) in
            make.top.equalTo(kStatusBarHeight)
            make.height.equalTo(44)
            make.left.equalTo(20)
        }
        tip1Lb.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(30)
            make.top.equalTo(200)
        }
        tip2Lb.snp.makeConstraints { (make) in
            make.left.equalTo(tip1Lb)
            make.top.equalTo(tip1Lb.snp.bottom).offset(5)
        }
        
        digitInput.snp.makeConstraints { (make) in
            make.top.equalTo(tip2Lb.snp.bottom).offset(30)
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-30)
            make.height.equalTo(50)
        }
        
        smsBtn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(30)
            make.top.equalTo(digitInput.snp.bottom).offset(10)
            make.height.equalTo(30)
        }
        
    }
    

    @objc func smsBtnTouchEvent(sender: BYCountDownButton){
        
       
        guard phonetext?.count > 0, self.checkPhoneLegal(phoneNum: phonetext) else {
            let toast = Toast(text: "请检查手机号码")
            toast.view.bottomOffsetPortrait = kScreenHeight / 2
            toast.show()
            return
        }
        BYNetwork.sendRequest(target: MultiTarget(MBLoginApi.sendSmsVaifyCode(phone: phonetext!)), showError: true, success: { (response) in
            if response?.code == 0{
                let toast = Toast(text: "短信发送成功")
                toast.view.bottomOffsetPortrait = kScreenHeight / 2
                toast.show()
                
                let _ = self.digitInput.becomeFirstResponder()
                // 开启计时器
                self.smsBtn.isCounting = true
                // 设置重新获取秒数
                self.smsBtn.remainingSeconds = 60
            }else{
                let toast = Toast(text: "获取验证码失败")
                toast.view.bottomOffsetPortrait = kScreenHeight / 2
                toast.show()
            }
        }) { (error) in
            let toast = Toast(text: "获取验证码失败")
            toast.view.bottomOffsetPortrait = kScreenHeight / 2
            toast.show()
            
        }
    }
    
    //验证手机号码正确性
    func checkPhoneLegal(phoneNum: String?) -> Bool {
        
        return String.isChinaPhoneLegal(phoneNo: phoneNum ?? "")
    }
    
    func getFuntionModelname(parameters: String) -> VJFuntionModel {
        
        let funtionModel = VJFuntionModel(jsonData: JSON.null)
        funtionModel.permissionName = parameters
        return  funtionModel
    }
    
    func digitsDidChange(digitInputView: DigitInputView) {
        if digitInputView.text.count == 6 {
            
            BYNetwork.sendRequest(target: MultiTarget(MBLoginApi.loginWithPhone(phone: phonetext!, smsCode: digitInputView.text)), showError: true, success: { (response) in
                if response?.code == 0{
        
                    let json = JSON.init(response?.data! as Any)
                
                    let LoginRspInfo =  MBLoginRspInfo(jsonData:json)
                    
                    LoginRspInfo.userInfo?.commonFuntion = [self.getFuntionModelname(parameters: "订单管理"),
                                                            self.getFuntionModelname(parameters: "商品管理"),
                                                            self.getFuntionModelname(parameters: "营销管理"),
                                                            self.getFuntionModelname(parameters: "我的精品库"),
                                                            self.getFuntionModelname(parameters: "公有商品库"),
                                                            self.getFuntionModelname(parameters: "平台活动申报")]
                    
                    LoginRspInfo.userInfo?.liveFuntion = [self.getFuntionModelname(parameters: "直播计划"),
                    self.getFuntionModelname(parameters: "直播间管理"),
                    self.getFuntionModelname(parameters: "主播管理"),
                    self.getFuntionModelname(parameters: "直播记录")]
                    
                    
                     print(LoginRspInfo.mapJSON())
                    
                    Defaults().set(LoginRspInfo.mapJSON(), for: KeySmallUserInfo)
                
                    //进入主界面
                    MBUserInfo.shared.showRootViewController()
                            
                }else{
                      let toast = Toast(text: MBStr.LoginSystem.verifyCodeValue)
                      toast.view.bottomOffsetPortrait = kScreenHeight / 2
                      toast.show()
                   }
                }) { (error) in
                
                    let toast = Toast(text: MBStr.LoginSystem.verifyCodeValue)
                    toast.view.bottomOffsetPortrait = kScreenHeight / 2
                    toast.show()
                            
                }
        
        }
    }
    


}
